package com.example.pulsar.service;

import com.example.pulsar.bean.InitParamBean;
import com.google.common.collect.Sets;
import org.apache.pulsar.client.admin.PulsarAdmin;
import org.apache.pulsar.client.impl.conf.ClientConfigurationData;
import org.apache.pulsar.common.policies.data.TenantInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @Auther: 141040
 * @Date: 3/26/2019 09:51
 * @Description:
 */
@Component
public class InitPulsarConfigure {

    @Value("${adminApiUrl}")
    private String adminApiUrl;

    public String init(InitParamBean initParamBean) {

        List<String> namespaces = null;
        TenantInfo tenantInfo = new TenantInfo();
        tenantInfo.setAdminRoles(Sets.newHashSet());
        //初始化租户与namespace
        try {
            PulsarAdmin pulsarAdmin = initPulsarAdmin();
            pulsarAdmin.tenants().createTenant(initParamBean.getTenant(), tenantInfo);
            pulsarAdmin.namespaces().createNamespace(initParamBean.getTenant()+"/"+initParamBean.getNamespace());

//            policies = pulsarAdmin.namespaces().getPolicies(initParamBean.getTenant()+"/"+initParamBean.getNamespace());
            namespaces = pulsarAdmin.namespaces().getNamespaces(initParamBean.getTenant());
        } catch (Exception e) {
            e.printStackTrace();
        }

        if(ObjectUtils.isEmpty(namespaces)||namespaces.size()==0) {
            return null;
        }

        return namespaces.get(0);
    }

    private PulsarAdmin initPulsarAdmin() throws Exception {
//        boolean useTls = false;
//        boolean tlsAllowInsecureConnection = false;
//        String tlsTrustCertsFilePath = null;
        ClientConfigurationData config = new ClientConfigurationData();
//        config.setUseTls(useTls);
//        config.setTlsAllowInsecureConnection(tlsAllowInsecureConnection);
//        config.setTlsTrustCertsFilePath(tlsTrustCertsFilePath);
        PulsarAdmin admin = new PulsarAdmin(adminApiUrl, config);
        return admin;
    }

}
